package com.lepu.app.fun.grow.play;

import java.io.File;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.config.UserConfig;
import com.app.utils.Const;
import com.app.utils.PlaySoundUtil;
import com.app.utils.SdLocal;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.utils.main.ImageUtilBase;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.grow.bean.PhotoItem;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;

public class PlayImageAutoActivity extends BaseFragmentActivity implements
		OnTopbarNewRightButtonListener {

	private static final int MSG_UPDATE_DATA = 100;

	private ImageView mImageView;
	private int mCurrentIndex = 0;
	private boolean mIsSample = true;
	private boolean mIsPlayAll = true;// 播放所有，从头开始播放
	private String mCurrentDateString = "";
	private boolean mIsPlayNet = false;// 播放网络下载的

	private FlakeView mFlakeView;
	private boolean mOnPause = false;

	private ArrayList<PhotoItem> mDataList;

	//private TextView mPlayTitleTextView;
	private TextView mPlayBottomTextView;
	private RelativeLayout mBottomMenuLayout;

	private String[] mSampleTopTitleArray;
	private String[] mSampleBottomTitleArray;

	private int mCurrentSpeed = 0;

	private ArrayList<String> mNetPlayList = null;
	private String mAlbumID;
	private String[] mNetTitleArray;
	
	private Animation mImageAnimation;
	private Animation mTextAnimation;

	@Override
	@SuppressLint({ "InflateParams", "ResourceAsColor" })
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

		mNeedStatusBar = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.grow_play_image_auto_activity);

		init();
	}

	@Override
	public void onResume() {
		super.onResume();

		if (mOnPause) {
			refreshImageData();
			if(mFlakeView != null)
			{
				mFlakeView.resume();
			}
		}
		mOnPause = false;

		// 播放音乐
		playMusic();
	}

	@Override
	public void onPause() {
		super.onPause();

		if(mFlakeView != null)
		{
			mFlakeView.pause();
		}

		mHandler.removeMessages(MSG_UPDATE_DATA);
		mOnPause = true;

		// 停止播放音乐
		PlaySoundUtil.getInstance().stop(null);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@SuppressLint("NewApi")
	private void init() {

		mImageAnimation = AnimationUtils.loadAnimation(this,
				R.anim.image_play_wave_scale);
		mTextAnimation = AnimationUtils.loadAnimation(this,
				R.anim.text_play_scale);
		
		Bundle data = getIntent().getExtras();
		if (data != null && data.size() > 0) {
			mIsSample = data.getBoolean("boolean_sample");
			mIsPlayAll = data.getBoolean("boolean_all");
			mCurrentDateString = data.getString("current_day");

			mIsPlayNet = data.getBoolean("IsPlayNet");
			mAlbumID = data.getString("AlbumId");
			mNetTitleArray = data.getStringArray("titleArray");
		}

		if (mIsPlayNet) {

			mNetPlayList = new ArrayList<String>();

			String folderPath = SdLocal.getAlbumHotPhotoFolder(this, mAlbumID);
			File file = new File(folderPath);
			File files[] = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				String path = files[i].getAbsolutePath();
				mNetPlayList.add(path);
			}

		} else if (!mIsSample) {

			String uid = MyApplication.getInstance().getLoginInfo().UserID + "";
			if (mIsPlayAll) {
				mDataList = PhotoItem.getAllPhotos(uid);
			} else {
				mDataList = PhotoItem.getPhotosByDate(uid, mCurrentDateString);
			}
		} else {
			mSampleTopTitleArray = getResources().getStringArray(
					R.array.array_play_sample_top_title);
			mSampleBottomTitleArray = getResources().getStringArray(
					R.array.array_play_sample_bottom_title);
		}

		//mPlayTitleTextView = (TextView) findViewById(R.id.playTitleTextView);
		mPlayBottomTextView = (TextView) findViewById(R.id.playBottomTextView);

		mBottomMenuLayout = (RelativeLayout) findViewById(R.id.bottomMenuLayout);
		ImageView menuUserImageView = (ImageView) findViewById(R.id.menuUserImageView);
		ImageView menuCancelImageView = (ImageView) findViewById(R.id.menuCancelImageView);
		menuUserImageView.setOnClickListener(mOnClickListener);
		menuCancelImageView.setOnClickListener(mOnClickListener);

		mImageView = (ImageView) findViewById(R.id.autoImageView);
		mImageView.setOnClickListener(mOnClickListener);

		// animation
		try{
			mFlakeView = new FlakeView(this);
			LinearLayout containLayout = (LinearLayout) findViewById(R.id.containLayout);
			containLayout.addView(mFlakeView);
			mFlakeView.addFlakes(mFlakeView.getNumFlakes());

			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
				mFlakeView.setLayerType(View.LAYER_TYPE_NONE, null);
			}
		}catch (Exception e){

		}

		// 设置当前速度
		String[] speedArray = getResources().getStringArray(
				R.array.array_play_speed);
		int index = UserConfig.getConfigInt(this,
				Const.SETTING_SPEED_INDEX_SELECTED, 0);
		mCurrentSpeed = Integer.parseInt(speedArray[index]);

		refreshImageData();
	}

	private void playMusic() {
		int index = UserConfig.getConfigInt(this,
				Const.SETTING_MUSIC_INDEX_SELECTED, 0);
		int playResId = R.raw.music0;
		switch (index) {
		case 0:
			playResId = R.raw.music0;
			break;
		case 1:
			playResId = R.raw.music1;
			break;
		case 2:
			playResId = R.raw.music2;
			break;

		default:
			break;
		}
		PlaySoundUtil.getInstance().play(this, playResId, true, null);
	}

	@SuppressWarnings("unused")
	private void showSelectPlayPop() {
		String[] array = getResources().getStringArray(
				R.array.array_pop_play_viewpager);
		new MyDialog(this).setSimpleItems(array, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (which == 0) {
					finish(true);

					Intent intent = new Intent(PlayImageAutoActivity.this,
							PlayImageUserActivity.class);
					intent.putExtra("boolean_sample", mIsSample);
					intent.putExtra("boolean_all", mIsPlayAll);// 播放当天的
					intent.putExtra("current_day", mCurrentDateString);
					intent.putExtra("IsPlayNet", mIsPlayNet);
					intent.putExtra("AlbumId", mAlbumID);
					intent.putExtra("titleArray", mNetTitleArray);
					startActivity(intent, true);
				} else {
					finish(true);
				}
			}
		}).create(null).show();
	}

	@SuppressLint("NewApi")
	private void refreshImageData() {
		if (mIsPlayNet) {

			mPlayBottomTextView.setText(mNetTitleArray[mCurrentIndex]);

			String path = mNetPlayList.get(mCurrentIndex);

			mImageView.startAnimation(mImageAnimation);
			mPlayBottomTextView.startAnimation(mTextAnimation);
			
			//Bitmap bitmap = ImageUtilBase.getBitmap(path);
			//mImageView.setImageBitmap(bitmap);
			UniversalImageLoadTool.disPlay("file://"+path, mImageView, 0);

			mCurrentIndex++;

			if (mCurrentIndex > mNetPlayList.size() - 1) {
				mCurrentIndex = 0;
			}

		} else if (mIsSample) {
			//mPlayTitleTextView.setText(mSampleTopTitleArray[mCurrentIndex]);
			mPlayBottomTextView.setText(mSampleBottomTitleArray[mCurrentIndex]);

			// play sample image
			try {
				mImageView.startAnimation(mImageAnimation);
				mPlayBottomTextView.startAnimation(mTextAnimation);
				
				String path = String.format("image_sample/%d.jpg",
						mCurrentIndex);
//				AssetManager assetManager = getAssets();
//				InputStream is = assetManager.open(path);
//				Bitmap bitmap = BitmapFactory.decodeStream(is);
//				mImageView.setImageBitmap(bitmap);
				UniversalImageLoadTool.disPlay(ImageUtilBase.getAssetImageUrl(path), mImageView, 0);
				
			} catch (Exception e) {
			}

			mCurrentIndex++;

			if (mCurrentIndex > Const.SAMPLE_PLAY_IMAGE_COUNT - 1) {
				mCurrentIndex = 0;
			}

		} else {
			// play custom image
			PhotoItem item = mDataList.get(mCurrentIndex);

//			int[] array = Utils.getCacuteTimeDayString(MyApplication
//					.getInstance().getLoginInfo().BabyBirthDate, item.addTime);
//
//			mPlayTitleTextView.setText(String.format("%d岁%d天", array[0],
//					array[1]));
			mPlayBottomTextView.setText(item.desc);

			mImageView.startAnimation(mImageAnimation);
			mPlayBottomTextView.startAnimation(mTextAnimation);
			
//			Bitmap bitmap = ImageUtilBase.getBitmap(item.imagePath);
//			mImageView.setImageBitmap(bitmap);
			UniversalImageLoadTool.disPlay("file://"+item.imagePath, mImageView, 0);

			mCurrentIndex++;

			if (mCurrentIndex > mDataList.size() - 1) {
				mCurrentIndex = 0;
			}
		}

		mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DATA, mCurrentSpeed);
	}

	private View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.autoImageView:

				// 弹出选择menu
				// showSelectPlayPop();

				int visible = mBottomMenuLayout.getVisibility();
				if (visible == View.GONE) {
					mBottomMenuLayout.setVisibility(View.VISIBLE);
					mPlayBottomTextView.setVisibility(View.GONE);
				} else {
					mBottomMenuLayout.setVisibility(View.GONE);
					mPlayBottomTextView.setVisibility(View.VISIBLE);
				}

				break;
			case R.id.menuUserImageView:

				finish(true);

				Intent intent = new Intent(PlayImageAutoActivity.this,
						PlayImageUserActivity.class);
				intent.putExtra("boolean_sample", mIsSample);
				intent.putExtra("boolean_all", mIsPlayAll);// 播放当天的
				intent.putExtra("current_day", mCurrentDateString);
				intent.putExtra("IsPlayNet", mIsPlayNet);
				intent.putExtra("AlbumId", mAlbumID);
				intent.putExtra("titleArray", mNetTitleArray);
				startActivity(intent, true);
				break;
			case R.id.menuCancelImageView:

				finish(true);
				break;

			default:
				break;
			}
		}
	};

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_UPDATE_DATA:

				refreshImageData();
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void onTopbarRightButtonSelected() {
		finish(true);
	}

	@Override
	public void onBackPressed() {
		finish(true);
	}
}
